<template>
  <div class="main">
    <div style="display: flex; justify-content: center">
      <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
        <el-menu-item index="/Shop">热门商店</el-menu-item>
        <el-menu-item index="/MyCollect">我的收藏</el-menu-item>
        <el-menu-item index="/ShoppingCart">购物车</el-menu-item>
        <el-menu-item index="/OrderCenter">订单中心</el-menu-item>
      </el-menu>
    </div>
    <br>
    <el-card class="collect-container">
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column prop="productName" label="产品"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleCancel(scope.row)">取消收藏</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="pagination"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          @current-change="handlePageChange"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import {queryCollectByPage, removeCollect} from "@/api/request/ShopRequest";

export default {
  name: "MyCollect",
  data() {
    return {
      activeIndex: '/MyCollect',
      queryParams: {
        page: 0,
        size: 10,
        userId: null
      },
      total: null,
      tableData: [],
      userInfo: {}
    }
  },
  methods: {
    handleSelect(key) {
      this.$router.push(key);
    },
    handleCancel(row) {
      this.$confirm('确定要取消收藏' + row.productName + '吗？', '提示', {
        type: 'warning'
      }).then(() => {
        removeCollect({productId: row.productId, userId: this.userInfo.id}).then(res => {
          if (res) {
            this.$message.success('取消收藏成功')
            this.getList()
          } else {
            this.$message.error('取消收藏失败')
          }
        })
      }).catch(() => {
      });
    },
    // 分页切换
    handlePageChange(page) {
      this.queryParams.page = page;
      this.getList()
    },
    getList() {
      if(!this.userInfo){
        this.$message.error('登录账号才可查看')
        return
      }

      this.queryParams.userId = this.userInfo.id
      queryCollectByPage(this.queryParams).then(res => {
        this.tableData = res.content
        this.total = res.totalElements
      })
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
.main {
  padding-top: 93px;
}

.collect-container {
  max-width: 800px;
  margin: 200px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
